package network.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author fank
 * @date 2018/03/20
 */
public class MyDecoder extends MessageToMessageDecoder<ByteBuf> {
    private final Charset charset;

    public MyDecoder() {
        this(Charset.defaultCharset());
    }

    public MyDecoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        //接收到字节大于4个字节了就处理。
        System.out.println(msg.toString(this.charset));
        if (msg.readableBytes() >= 4) {
            String message = msg.toString(this.charset);
            out.add(message.substring(4, message.length()));
        }
    }
}
